<?php

/**
 * 小程序入口
 * [WeEngine System] Copyright (c) 2013 WE7.CC
 */
defined('IN_IA') or exit('Access Denied');

class Kbwdl_nicksceneryModuleWxapp extends WeModuleWxapp
{

    public function doPageIndex()
    {
        require __DIR__ . '/public/uapi.php';
    }

    /**
     * 发起支付功能
     */
    public function doPagePay()
    {
        global $_GPC, $_W;
        $uniacid = $_W['uniacid'];
        $openid = $_W['openid'];

        $fee = trim($_GPC['money']);
        $order_no = trim($_GPC['order_no']);

        //查询是否有订单
        $order = pdo_fetch("select * from " . tablename('knscy_orders') . " where `order_no` = :order_no", ['order_no' => $order_no]);
        if (empty($order)) {
            return $this->result(1, '订单参数错误');
        }
        $order_details = pdo_fetch("select * from " . tablename('knscy_order_ticket') . " where `order_id` = :order_id", ['order_id' => $order['id']]);
        if (empty($order_details)) {
            return $this->result(1, '订单详情参数错误');
        }
        if($order['status_label'] !== 'unpaid'){
            return $this->result(1, '订单无需支付');
        }
        if($fee <=0 ){
            return $this->result(1, '金额0无需支付');
        }
        //检查支付金额= 订单金额
        $total_price = max(0, $order['order_money'] - $order['discount_money']);
        if($fee != $total_price){
            return $this->result(1, '支付金额不正确');
        }

        /* 生成下单记录 */
        pdo_insert("knscy_order_logs", array(
            'create_time' => TIMESTAMP,
            'update_time' => TIMESTAMP,
            'order_id' => $order['id'],
            'order_no' => $order_no,
            'uniacid' => $uniacid,
            'tag' => 'wxapp.doPagePay',
            'content' => 'doPagePay => 订单发起支付'
        ));
        //订单状态发起支付//发起支付
        pdo_update('knscy_orders',
            [ 'pay_status' => 1 ],//进入支付
            ['id' => $order['id']]
        );
        /* 构造支付参数 */
        $pay_order = array(
            'tid' => $order_no,
            'ordersn'=>$order_no,
            'user' => $_W['member']['uid'],
            'fee' => floatval($fee),
            'title' => $order_details['ticket_title'] . " " . $order_details['ticket_subtitle'],
        );
        /* 生成支付参数，返回给小程序端 */
        $pay_params =  $this->pay($pay_order);

        if (is_error($pay_params)) {
            pdo_insert("knscy_order_logs", array(
                'create_time' => TIMESTAMP,
                'update_time' => TIMESTAMP,
                'order_id' => $order['id'],
                'order_no' => $order_no,
                'uniacid' => $uniacid,
                'tag' => 'wxapp.doPagePay',
                'content' => 'doPagePay => 发起支付参数有误，请重试'
            ));
            return $this->result(1, '发起支付参数有误，请重试');
        }
        //订单状态发起支付//发起支付
        pdo_update('knscy_orders',
            [ 'pay_status' => 2 ], //发起支付
            ['id' => $order['id']]
        );
        return $this->result(0, '', $pay_params);
    }

    /**
     * 支付处理
     */
    public function payResult($log)
    {
        global $_GPC, $_W;
        $uniacid = $log['uniacid'];
        $openid = $_W['openid'];
        $uid = $log['tag']['uid'];
        /* load()->func('logging');
          logging_run($log); */

        if ($log['tid']) {
            $order_no = $log['tid'];
            $order = pdo_fetch("select * from " . tablename('knscy_orders') .
                " where `order_no` = :order_no and uniacid = :uniacid ",
                ['order_no' => $order_no,'uniacid' => $uniacid]
            );

            if ($log['result'] == 'success' && $log['from'] == 'notify' && !empty($order)) {
                /* 保存支付通知成记录 */
                pdo_insert("knscy_order_logs", array(
                    'create_time' => TIMESTAMP,
                    'update_time' => TIMESTAMP,
                    'order_id' => $order['id'],
                    'order_no' => $order_no,
                    'uniacid' => $uniacid,
                    'tag' => 'wxapp.payResult',
                    'content' => 'payResult => 通知,notify => 成功, DATA => '.json_encode($log),
                ));
                /* 完成支付订单 */
                pdo_update('knscy_orders',
                    [
                        'status_label' => 'process',
                        'pay_status' => 3, //支付成功
                        'pay_type' =>1, //微信支付
                        'order_status' => 21,
                    ],
                    ['id' => $order['id']]
                );
                /*出票修改为生效*/
                $where = ['order_no'=> $order_no ];
                $sns = pdo_fetchcolumn("select `ticket_sn` from ".tablename('knscy_ticket_out') ." where order_no = :order_no", $where);
                pdo_update('knscy_ticket_out',['sort' =>0, 'start_time'=>date('Y-m-d H:i:s' )],$where);

                pdo_insert("knscy_order_logs", [
                    'order_id' => $order['id'],
                    'order_no' => $order_no,
                    'tag' => 'pay.notify.process',
                    'content' => '订单支付完成，门票(卡)生效，票NO => ' . implode(',', $sns),
                ]);
                return $this->result(0, '支付成功', $log);
            }
        }

        return $this->result(0, '支付失败', $log);
    }
}